import React, { useState, useEffect, useRef } from 'react';
import { MessageCircle, X, Send, Minimize2 } from 'lucide-react';
import { useLanguage } from '../contexts/LanguageContext';

interface Message {
  id: string;
  type: 'user' | 'bot';
  content: string;
  timestamp: Date;
  isTyping?: boolean;
}

const ChatWidget = () => {
  const [isOpen, setIsOpen] = useState(false);
  const [isMinimized, setIsMinimized] = useState(false);
  const [messages, setMessages] = useState<Message[]>([]);
  const [inputValue, setInputValue] = useState('');
  const [typingMessage, setTypingMessage] = useState<string>('');
  const [isTyping, setIsTyping] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const hasShownWelcome = useRef(false);
  const { language } = useLanguage();

  // Simulate typing effect
  const simulateTyping = (text: string, messageId: string) => {
    setIsTyping(true);
    setTypingMessage('');
    let currentIndex = 0;

    const typingInterval = setInterval(() => {
      if (currentIndex <= text.length) {
        setTypingMessage(text.slice(0, currentIndex));
        currentIndex++;
      } else {
        clearInterval(typingInterval);
        setIsTyping(false);
        setTypingMessage('');
        setMessages(prev => [...prev, {
          id: messageId,
          type: 'bot',
          content: text,
          timestamp: new Date()
        }]);
      }
    }, 30); // Typing speed
  };

  // Welcome message
  useEffect(() => {
    if (isOpen && !hasShownWelcome.current) {
      hasShownWelcome.current = true;
      const welcomeText = language === 'zh-CN' 
        ? '您好！欢迎使用 KernelProxy 客服支持。我是您的智能助手，有什么可以帮助您的吗？'
        : 'Hello! Welcome to KernelProxy customer support. I\'m your virtual assistant. How can I help you today?';
      
      simulateTyping(welcomeText, 'welcome');
    }
  }, [isOpen, language]);

  // Auto scroll to bottom
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages, typingMessage]);

  // Handle send message
  const handleSend = () => {
    if (!inputValue.trim()) return;

    const userMessage: Message = {
      id: `user-${Date.now()}`,
      type: 'user',
      content: inputValue,
      timestamp: new Date()
    };

    setMessages(prev => [...prev, userMessage]);
    setInputValue('');

    // Simulate bot response
    setTimeout(() => {
      const botResponse = getBotResponse(inputValue);
      simulateTyping(botResponse, `bot-${Date.now()}`);
    }, 500);
  };

  // Simple bot responses
  const getBotResponse = (userInput: string): string => {
    const input = userInput.toLowerCase();
    
    if (language === 'zh-CN') {
      if (input.includes('价格') || input.includes('费用') || input.includes('多少钱')) {
        return '我们提供多种代理套餐。动态住宅 IPv6 起价 $0.712/GB，静态住宅 IPv6 起价 $0.40/IP/月，数据中心 IPv6 起价 $0.20/IP/月。您可以访问价格页面查看详细信息。';
      }
      if (input.includes('试用') || input.includes('免费')) {
        return '目前我们提供 7 天退款保证。您可以先购买我们的服务，如果不满意可以在 7 天内申请全额退款。';
      }
      if (input.includes('支付') || input.includes('付款')) {
        return '我们支持多种支付方式，包括信用卡、PayPal、加密货币等。所有支付都是安全加密的。';
      }
      if (input.includes('国家') || input.includes('地区') || input.includes('位置')) {
        return '我们的代理服务覆盖全球 200+ 个国家和地区。您可以在选购页面选择所需的国家和地区。';
      }
      if (input.includes('技术') || input.includes('支持') || input.includes('帮助')) {
        return '我们提供 24/7 全天候技术支持。您可以通过邮件、在线客服或提交工单联系我们的技术团队。';
      }
      return '感谢您的咨询。如需更多帮助，请访问我们的文档页面或联系人工客服。我们的支持团队随时为您服务！';
    } else {
      if (input.includes('price') || input.includes('cost') || input.includes('how much')) {
        return 'We offer various proxy packages. Dynamic Residential IPv6 starts at $0.712/GB, Static Residential IPv6 starts at $0.40/IP/month, and Datacenter IPv6 starts at $0.20/IP/month. Visit our pricing page for details.';
      }
      if (input.includes('trial') || input.includes('free')) {
        return 'We offer a 7-day money-back guarantee. You can try our service, and if you\'re not satisfied, request a full refund within 7 days.';
      }
      if (input.includes('payment') || input.includes('pay')) {
        return 'We accept multiple payment methods including credit cards, PayPal, and cryptocurrencies. All payments are securely encrypted.';
      }
      if (input.includes('country') || input.includes('location') || input.includes('region')) {
        return 'Our proxy service covers 200+ countries and regions worldwide. You can select your desired location on our purchase pages.';
      }
      if (input.includes('support') || input.includes('help') || input.includes('technical')) {
        return 'We provide 24/7 technical support. You can reach our support team via email, live chat, or by submitting a ticket.';
      }
      return 'Thank you for your inquiry. For more assistance, please visit our documentation or contact our human support team. We\'re here to help!';
    }
  };

  // Handle Enter key
  const handleKeyPress = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSend();
    }
  };

  return (
    <div className="fixed bottom-6 right-6 z-50">
      {/* Chat Button */}
      {!isOpen && (
        <button
          onClick={() => setIsOpen(true)}
          className="group relative flex items-center justify-center w-14 h-14 bg-gradient-to-r from-[#00d4ff] to-[#0099cc] hover:from-[#00e5ff] hover:to-[#00aadd] text-white rounded-full shadow-lg hover:shadow-xl transition-all duration-300 transform hover:scale-110"
          aria-label="Open chat"
        >
          <MessageCircle size={24} className="animate-pulse" />
          <span className="absolute -top-1 -right-1 w-4 h-4 bg-red-500 rounded-full animate-ping"></span>
          <span className="absolute -top-1 -right-1 w-4 h-4 bg-red-500 rounded-full"></span>
        </button>
      )}

      {/* Chat Window */}
      {isOpen && (
        <div
          className={`flex flex-col bg-white dark:bg-gray-800 rounded-2xl shadow-2xl border border-gray-200 dark:border-gray-700 transition-all duration-300 ${
            isMinimized ? 'w-80 h-16' : 'w-80 sm:w-96 h-[500px]'
          }`}
        >
          {/* Header */}
          <div className="flex items-center justify-between px-4 py-3 bg-gradient-to-r from-[#0f1c3f] to-[#1a2a5e] dark:from-gray-900 dark:to-gray-800 text-white rounded-t-2xl border-b border-white/10">
            <div className="flex items-center gap-3">
              <div className="relative">
                <div className="w-10 h-10 bg-gradient-to-r from-[#00d4ff] to-[#0099cc] rounded-full flex items-center justify-center">
                  <MessageCircle size={20} />
                </div>
                <span className="absolute bottom-0 right-0 w-3 h-3 bg-green-500 border-2 border-white dark:border-gray-900 rounded-full"></span>
              </div>
              <div>
                <h3 className="font-bold text-sm">
                  {language === 'zh-CN' ? 'KernelProxy 客服' : 'KernelProxy Support'}
                </h3>
                <p className="text-xs text-gray-300">
                  {language === 'zh-CN' ? '在线' : 'Online'}
                </p>
              </div>
            </div>
            <div className="flex items-center gap-2">
              <button
                onClick={() => setIsMinimized(!isMinimized)}
                className="p-1.5 hover:bg-white/10 rounded-lg transition-colors"
                aria-label="Minimize"
              >
                <Minimize2 size={18} />
              </button>
              <button
                onClick={() => setIsOpen(false)}
                className="p-1.5 hover:bg-white/10 rounded-lg transition-colors"
                aria-label="Close"
              >
                <X size={18} />
              </button>
            </div>
          </div>

          {/* Messages */}
          {!isMinimized && (
            <>
              <div className="flex-1 overflow-y-auto p-4 space-y-4 bg-gray-50 dark:bg-gray-900">
                {messages.map((message) => (
                  <div
                    key={message.id}
                    className={`flex ${message.type === 'user' ? 'justify-end' : 'justify-start'}`}
                  >
                    <div
                      className={`max-w-[80%] px-4 py-2 rounded-2xl ${
                        message.type === 'user'
                          ? 'bg-gradient-to-r from-[#00d4ff] to-[#0099cc] text-white rounded-br-sm'
                          : 'bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 border border-gray-200 dark:border-gray-700 rounded-bl-sm shadow-sm'
                      }`}
                    >
                      <p className="text-sm whitespace-pre-wrap break-words">{message.content}</p>
                      <p
                        className={`text-xs mt-1 ${
                          message.type === 'user'
                            ? 'text-white/70'
                            : 'text-gray-500 dark:text-gray-400'
                        }`}
                      >
                        {message.timestamp.toLocaleTimeString(language === 'zh-CN' ? 'zh-CN' : 'en-US', {
                          hour: '2-digit',
                          minute: '2-digit'
                        })}
                      </p>
                    </div>
                  </div>
                ))}

                {/* Typing indicator */}
                {isTyping && typingMessage && (
                  <div className="flex justify-start">
                    <div className="max-w-[80%] px-4 py-2 rounded-2xl bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 border border-gray-200 dark:border-gray-700 rounded-bl-sm shadow-sm">
                      <p className="text-sm whitespace-pre-wrap break-words">
                        {typingMessage}
                        <span className="inline-block w-0.5 h-4 bg-[#00d4ff] ml-1 animate-pulse"></span>
                      </p>
                    </div>
                  </div>
                )}

                {/* Typing dots */}
                {isTyping && !typingMessage && (
                  <div className="flex justify-start">
                    <div className="px-4 py-3 rounded-2xl bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-bl-sm shadow-sm">
                      <div className="flex gap-1">
                        <span className="w-2 h-2 bg-gray-400 dark:bg-gray-600 rounded-full animate-bounce" style={{ animationDelay: '0ms' }}></span>
                        <span className="w-2 h-2 bg-gray-400 dark:bg-gray-600 rounded-full animate-bounce" style={{ animationDelay: '150ms' }}></span>
                        <span className="w-2 h-2 bg-gray-400 dark:bg-gray-600 rounded-full animate-bounce" style={{ animationDelay: '300ms' }}></span>
                      </div>
                    </div>
                  </div>
                )}

                <div ref={messagesEndRef} />
              </div>

              {/* Input */}
              <div className="p-4 bg-white dark:bg-gray-800 border-t border-gray-200 dark:border-gray-700 rounded-b-2xl">
                <div className="flex gap-2">
                  <input
                    type="text"
                    value={inputValue}
                    onChange={(e) => setInputValue(e.target.value)}
                    onKeyPress={handleKeyPress}
                    placeholder={language === 'zh-CN' ? '输入消息...' : 'Type a message...'}
                    className="flex-1 px-4 py-2 bg-gray-100 dark:bg-gray-900 text-gray-900 dark:text-gray-100 border border-gray-200 dark:border-gray-700 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#00d4ff] focus:border-transparent transition-all"
                    disabled={isTyping}
                  />
                  <button
                    onClick={handleSend}
                    disabled={!inputValue.trim() || isTyping}
                    className="px-4 py-2 bg-gradient-to-r from-[#00d4ff] to-[#0099cc] hover:from-[#00e5ff] hover:to-[#00aadd] text-white rounded-lg transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed transform hover:scale-105 active:scale-95"
                    aria-label="Send"
                  >
                    <Send size={18} />
                  </button>
                </div>
              </div>
            </>
          )}
        </div>
      )}
    </div>
  );
};

export default ChatWidget;
